package com.fcl.blog.web;

import com.fcl.blog.comment.Result;
import com.fcl.blog.po.Admin;
import com.fcl.blog.po.User;
import com.fcl.blog.service.UserServie;
import com.fcl.blog.utils.TokenUtil;
import com.fcl.blog.vo.AdminVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author 付
 * @Date 2023/10/25 14:16
 * @Version 1.0
 * @description
 * @since 1.0
 */
@RestController
@RequestMapping("/admin")
@Slf4j
public class LoginController {

    @Autowired
    private UserServie userServie;

    @PostMapping("/login")
    public Result getAdmin(@RequestBody AdminVo admin,HttpServletRequest request){
        if (admin==null){
            return Result.error("抱歉，获取登录信息失败");
        }
        Admin admin1 = userServie.selectByUsernameAndPassword(admin.getUsername(), admin.getPassword());
        if (admin1==null){
            return Result.error("抱歉，账号，或密码错误");
        }
        String username = admin1.getUsername();
        String password = admin1.getPassword();

        HttpSession session = request.getSession();
        session.setAttribute("username",username);
        session.setAttribute("password",password);

        String jwtToken = TokenUtil.getJwtToken(username,password);
        return Result.success("登录成功",jwtToken);
    }

    @GetMapping("/userLogin")
    public Result getUser(@RequestBody User user, HttpSession session){
        if (user==null){
            return Result.error("抱歉，获取登录信息失败");
        }
        User user1 = userServie.selectByUsernameAndPasswordToUser(user.getUsername(), user.getPassword());
        if (user1==null){
            return Result.error("抱歉，账号，或密码错误");
        }
        String jwtToken = TokenUtil.getJwtToken(user1.getUsername(), user1.getPassword());
        session.setAttribute("token",jwtToken);
        return Result.success("登录成功",jwtToken);
    }
}
